const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::staff');
const router = require('koa-router')();
exports = module.exports = router;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;

const _ = require('lodash');
const util = require(global.prefixPath + '/commons/util');
const site_service = require(global.prefixPath + '/services/site');
const info_service = require(global.prefixPath + '/services/info');
const categories = require(global.prefixPath + '/data/industries.json');


router.get('/:city/detail/:id', async (ctx, next) => {

    try {
        // 推广部分
        let fields = {adsenses: 1, _id: 0};
        let adsenses = (await site_service.findById(ctx.site._id, fields)).adsenses;
        let allids = [];
        for (let key in adsenses) {
            allids = allids.concat(adsenses[key]);
        }
        allids = util.toObjectId(allids);

        let allads = await info_service.findByIds(allids);

        // 组合数据
        for (let key in adsenses) {
            let ads = _.filter(allads, (val) => {
                return _.indexOf(adsenses[key], val._id.toString()) >= 0;
            });
            adsenses[key] = ads;
        }
        // ctx.state.adsenses = adsenses;
        // 推广 end


        let user_info = ctx.state.userinfo ? ctx.state.userinfo.pub : '';
        let info_id = ctx.params.id;
        // let oid = new ObjectId(info_id);
        // let update = {
        //     query: {_id: oid},
        //     update: {$inc: {viewCount: 1}}
        // };
        // let updateResult = await info_service.findAndModify(update.query, update.update);
        // console.log(updateResult)
        let result = await info_service.findById(info_id);
        if (user_info) {
            result.pub = user_info;
        }
        if (adsenses) {
            result.adsenses = adsenses;
        }

        console.log(result);
        console.log(ctx.params.city);
        ctx.state.info = result;
    } catch (err) {
        throw err;
    }

    return await ctx.render('detail/index');
});
